-module(my_db).
-export([start/0,stop/0,write/2,delete/1,read/1,match/1]).
-export([init/0]).

start() ->
    register(my_db, spawn(?MODULE, init, [])),ok.
stop() -> call({stop}).
write(Key, Element) -> call({write, {Key, Element}}). 
delete(Key) -> call({delete, {Key}}).
read(Key) -> call({read, {Key}}).
match(Element) -> call({match, {Element}}).

call(Msg) ->
    my_db ! {request, self(), Msg},
    receive {reply, Reply} -> Reply end.    

reply(From, Msg) ->
    From ! {reply, Msg}.

init() ->
    loop(db:new()).

loop(Db) ->
    receive
	{request, From, {stop}} ->
	    db:destroy(Db),
	    reply(From, ok);
	{request, From, {write, {Key, Element}}} ->
	    NewDb = db:write(Key, Element, Db),
	    reply(From, ok),
	    loop(NewDb);
	{request, From, {delete, {Key}}} ->
	    NewDb = db:delete(Key, Db),
	    reply(From, ok),
	    loop(NewDb);
	{request, From, {read, {Key}}} ->
	    Result = db:read(Key, Db),
	    reply(From, Result),
	    loop(Db);
	{request, From, {match, {Element}}} ->
	    Result = db:match(Element, Db),
	    reply(From, Result),
	    loop(Db)
    end.



	     
